//                       .::::.
//                     .::::::::.
//                    :::::::::::
//                 ..:::::::::::'
//              '::::::::::::'
//                .::::::::::
//           '::::::::::::::..
//                ..::::::::::::.
//              ``::::::::::::::::
//               ::::``:::::::::'        .:::.
//              ::::'   ':::::'       .::::::::.
//            .::::'      ::::     .:::::::'::::.
//           .:::'       :::::  .:::::::::' ':::::.
//          .::'        :::::.:::::::::'      ':::::.
//         .::'         ::::::::::::::'         ``::::.
//     ...:::           ::::::::::::'              ``::.
//    ```` ':.          ':::::::::'                  ::::..
//                       '.:::::'                    ':'````..
package com.xw.service;

import com.github.pagehelper.PageHelper;
import com.google.common.collect.Maps;
import com.xw.dao.NewsMapper;
import com.xw.model.News;
import com.xw.model.User;
import com.xw.util.AppUtil;
import com.xw.util.JsonData;
import com.xw.vo.NewsVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
@Transactional(rollbackFor = Exception.class)
public class NewsServiceImpl implements NewsService {

    @Resource
    private NewsMapper newsMapper;

    @Override
    public Map findNewsById(String id) {
        NewsVo newsVo = newsMapper.findNewsById(id);
        return JsonData.success(newsVo);
    }

    @Override
    public Map findNews(Integer page, Integer limit) {
        int totalPage = newsMapper.findNews().size();

        if (page != null && limit !=null){
            PageHelper.startPage(page,limit,false);
        }
        List<NewsVo> list = newsMapper.findNews();
        Map map = Maps.newHashMap();
        map.put("list",list);
        map.put("totalPage",totalPage);
        return JsonData.success(map);
    }

    @Override
    public Map edit(News news) {
        int flag = newsMapper.updateByPrimaryKeySelective(news);
        return JsonData.returnMap(flag);
    }

    @Override
    public News findByKeyId(String id) {
        return newsMapper.selectByPrimaryKey(id);
    }

    @Override
    public Map del(String id) {
        int flag = newsMapper.deleteByPrimaryKey(id);
        return JsonData.returnMap(flag);
    }

    @Override
    public Map add(HttpSession session, News news) {
        User user = (User) session.getAttribute("user");
        news.setId(AppUtil.uuid());
        news.setCreateTime(new Date());
        news.setUserId(user.getUserId());
        int flag = newsMapper.insertSelective(news);
        return JsonData.returnMap(flag);
    }

    @Override
    public List<NewsVo> findByWhere(String newsName) {
        return newsMapper.findByWhere(newsName);
    }
}
